<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" Async="true" %>
<%@ Import Namespace="ACM.cmsarea08" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Permissions" %>
<%@ Import Namespace="System.Security.Principal" %>


<script language="c#" runat="server">
	private int NewsTimeOffset = 14;
	
	void Page_Load(object o, EventArgs e) {
		Response.Cache.SetCacheability(HttpCacheability.NoCache);
		if(Request.Params["op"]==null) {Response.Write("no op"); return; }
		string op = Request.Params["op"].ToString();

		/* embed commands */
		if(op=="newartlist") {
			LoadArt(true);
			return;
		}
		if(op=="lastartlist") {
			LoadArt(false);
			return;
		}
		if(op=="newcatlist") {
			LoadCat(true,true);
			return;
		}
		if(op=="lastcatlist") {
			LoadCat(false,true);
			return;
		}
		if(op=="newsezlist") {
			LoadCat(true,false);
			return;
		}
		if(op=="lastsezlist") {
			LoadCat(false,false);
			return;
		}
		if(op=="lastuserslist") {
			LoadUsers(true,false);
			return;
		}
		if(op=="newuserslist") {
			LoadUsers(false,false);
			return;
		}
		if(op=="onlineuserslist") {
			LoadUsers(true,true);
			return;
		}
		
		if(op=="lockcount") {
			object ev = Request.Params["source"];
			if(ev==null) return;
			LoadLockCount(ev.ToString());
		}
		if(op=="checkfile") {
			object ev = Request.Params["source"];
			if(ev==null) return;
			CheckPermissionFile(ev.ToString());
		}
		if(op=="checkdir") {
			object ev = Request.Params["source"];
			if(ev==null) return;
			CheckPermissionDir(ev.ToString());
		}	
		
		if(op=="getloglist") {
			object ev = Request.Params["source"];
			bool loglist =false;
			if(ev!=null) loglist=true;
			getLogList(loglist);
		}	
		if(op=="readfile") {
			object ev = Request.Params["source"];
			if(ev==null) return;
			readFile(ev.ToString());
		}		
	}	
	void WriteCookie(string cosa, string rate) {
		HttpCookie myCookie = new HttpCookie("Default");
		myCookie[cosa] = rate;
		myCookie.Expires = DateTime.Now.AddDays(1);
		Response.Cookies.Add(myCookie);
	}
	
	bool ReadCookie(string cosa) {
		if (Request.Cookies["Default"] != null)
		{
			if (Request.Cookies["Default"][cosa] != null)
			{ return true; } 
		} 
		return false;
	}
	string ReadEditCookie(string cosa) {
		if (Request.Cookies[cosa] != null)
		{
			return HttpUtility.UrlDecode(HttpUtility.HtmlDecode(Request.Cookies[cosa].Value.ToString()));
		} 
		return string.Empty;
	}
		
	string SqlTesto (string text) {
		return ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(text);
	
	}	
		
		
	void LoadArt(bool newArt) {
		string tbPrefix = ACM.cmsarea08.DBManager.mainConnection.TablePrefix;
		const string nullo = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<dato></dato>";
		string joina = "";
		
		if(ACM.cmsarea08.mainconfiguration.MainConf.ApplyContentFilter && !ACM.cmsarea08.Users.CurrentUser.isRuolo("SysAdm") ) {
				object oCheck = ACM.cmsarea08.DBManager.mainConnection.Standard_SC("select count(id) from "+tbPrefix+"contenutiruoli where " +
				                                    " instr('" + string.Join("~",ACM.cmsarea08.Users.CurrentUser.Ruoli) + "',ruolo)>0 ; ");
				
				bool applyJoin = false;
				if(oCheck == null) 
						applyJoin=false;
				else {
					if(oCheck is byte[] ) 
						if(System.Text.Encoding.UTF8.GetString((byte[])oCheck)!="0") applyJoin=true; else applyJoin=false;
					else
						if(oCheck.ToString()!="0") applyJoin=true; else applyJoin=false;
				}
				if(applyJoin) {
					joina+= "inner join " + tbPrefix + "contenutiruoli as ruoli " +
				 		"on ( INSTR('" + string.Join("~",ACM.cmsarea08.Users.CurrentUser.Ruoli) + "',ruoli.ruolo)>0 and " +
				 		" ( " +
								"(ruoli.tipo='A' and ruoli.id=cont.id "+(ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua==ACM.cmsarea08.LanguageModel.All?
				 					 "or INSTR(ruoli.permessi,'T')>0 and ruoli.id=cont.tradotto_da":"")+") or " +
								"(ruoli.tipo='C' and ruoli.id=cont.cat_id " + " ) or " +
								"(ruoli.tipo='S' and ruoli.id=cont.sez_id "+ ")))";
				
				}
			}
			
		DataSet ds = ACM.cmsarea08.DBManager.mainConnection.Helper_Dataset(" " +
		"SELECT if((DATE_SUB(Now(), interval " + NewsTimeOffset.ToString() + " day)<cont.data_ins),'1','0') as newrec, cont.data_mod,titolo,cont.id, "+
		"(select nome_lingua from "+tbPrefix+"lingue where cultureinfo=lingua) as lingua, cont.enabled, sez_id, cat_id,  " +
		"(select username from "+tbPrefix+"utenti where "+tbPrefix+"utenti.id = cont.autore) as autorename,  " +
		"(select titolo from "+tbPrefix+"contenuti_manager where "+tbPrefix+"contenuti_manager.id = sez_id) as sezioname,  " +
		"(select titolo from "+tbPrefix+"contenuti_manager where "+tbPrefix+"contenuti_manager.id = cat_id) as catename,  " +
		"cont.autore,  " +
		"ifnull((select username from "+tbPrefix+"utenti where "+tbPrefix+"utenti.id = upd_id),'') as editorname,  " +
		"upd_id,deleting FROM "+tbPrefix+"contenuti as cont " + joina + " " +
		(newArt?" where cont.enabled ='0' or upd_id!='-1' or deleting<>'0' ":"") +
		" order by cont.data_mod desc limit 10;");
		

		if(ds==null) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables[0].Rows.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		ds.Tables[0].Columns.Add("url");	
		string sect = "";
		foreach(DataRow dr in ds.Tables[0].Rows) {
			string columns = "";
			for(int i = 0; i<ds.Tables[0].Columns.Count; i++) {
				string dato = "";
				if(dr[i] is byte[]) 
					dato = System.Text.Encoding.UTF8.GetString((byte[])dr[i]);
				else if (dr[i] is DateTime) 
					dato = ((DateTime)dr[i]).ToShortDateString();
				else{
					if(ds.Tables[0].Columns[i].ColumnName == "url"){
						dato = "/administration/core/edit_contenuti.aspx?new=0&amp;idf=A" + 
						dr["sez_id"].ToString() + "~" + 
						dr["cat_id"].ToString() + "~" + 
						dr["id"].ToString();
					}else
						dato = dr[i].ToString();
				}
				columns+=(
					string.Format("<{0}><![CDATA[{1}]]></{0}>", ds.Tables[0].Columns[i].ToString().ToLower(),HttpUtility.HtmlDecode(dato)));
			}
		
			if(columns!="") 		
				sect += "<dato>"+columns+"</dato>";
		}
		sect = "<dati>" + sect + "</dati>";
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+sect);
	}	
	
	
	void LoadCat(bool newCat,bool category) {
		string tbPrefix = ACM.cmsarea08.DBManager.mainConnection.TablePrefix;
		const string nullo = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<dato></dato>";
		string joina = "";
		
		if(ACM.cmsarea08.mainconfiguration.MainConf.ApplyContentFilter && !ACM.cmsarea08.Users.CurrentUser.isRuolo("SysAdm") ) {
				object oCheck = ACM.cmsarea08.DBManager.mainConnection.Standard_SC("select count(id) from "+tbPrefix+"contenutiruoli where " +
				                                    " instr('" + string.Join("~",ACM.cmsarea08.Users.CurrentUser.Ruoli) + "',ruolo)>0 ; ");
				
				bool applyJoin = false;
				if(oCheck == null) 
						applyJoin=false;
				else {
					if(oCheck is byte[] ) 
						if(System.Text.Encoding.UTF8.GetString((byte[])oCheck)!="0") applyJoin=true; else applyJoin=false;
					else
						if(oCheck.ToString()!="0") applyJoin=true; else applyJoin=false;
				}
				if(applyJoin) {
					joina = "inner join " + tbPrefix + "contenutiruoli as ruoli " +
					 					"on ( INSTR('" + string.Join("~",ACM.cmsarea08.Users.CurrentUser.Ruoli) + "',ruoli.ruolo)>0 and (" +
					 					(category?"ruoli.id=cont.figliodi and ruoli.tipo='S' or ":"") +
					 					"ruoli.id=cont.id and cont.tipo=ruoli.tipo " +
					 					(ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua==ACM.cmsarea08.LanguageModel.All?
					 					 "or INSTR(ruoli.permessi,'T')>0 and ruoli.id=cont.tradotto_da":"") + ")) ";
									
				
				}
			}
		
		
		
		
		
		
		DataSet ds = ACM.cmsarea08.DBManager.mainConnection.Helper_Dataset(" " +
		"SELECT if((DATE_SUB(Now(), interval " + NewsTimeOffset.ToString() + " day)<cont.data_ins),'1','0') as newrec, cont.data_mod," + 
		"(select nome_lingua from "+tbPrefix+"lingue where cultureinfo=lingua) as lingua,titolo,cont.id, cont.enabled,  " +
		"(select username from "+tbPrefix+"utenti where "+tbPrefix+"utenti.id = cont.autore) as autorename,  " +
		"cont.autore,figliodi,  " +
		"ifnull((select username from "+tbPrefix+"utenti where "+tbPrefix+"utenti.id = upd_id),'') as editorname,  " +
		"upd_id,deleting FROM "+tbPrefix+"contenuti_manager as cont " + joina + " " +
		"where cont.tipo='"+(category?"C":"S")+"' " + (newCat?" and (cont.enabled ='0' or upd_id!='-1' or deleting<>'0') ":"") +
		" order by cont.data_mod desc limit 10;");
		
		

			if(ds==null) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables[0].Rows.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}		
		ds.Tables[0].Columns.Add("url");
		string sect = "";
		
		foreach(DataRow dr in ds.Tables[0].Rows) {
			string columns = "";
			
			for(int i = 0; i<ds.Tables[0].Columns.Count; i++) {
				string dato = "";
				if(dr[i] is byte[]) 
					dato = System.Text.Encoding.UTF8.GetString((byte[])dr[i]);
				else if (dr[i] is DateTime) 
					dato = ((DateTime)dr[i]).ToShortDateString();
				else{
					if(ds.Tables[0].Columns[i].ColumnName == "url"){
						dato = "/administration/core/edit_" + (category?"categoria":"sezione") + ".aspx?new=0&amp;idf=" + 
						(category?"C"+dr["figliodi"].ToString() + "~":"S") + 
						dr["id"].ToString();
					}else
						dato = dr[i].ToString();
				}
				
				columns+=(
					string.Format("<{0}><![CDATA[{1}]]></{0}>", ds.Tables[0].Columns[i].ToString().ToLower(),HttpUtility.HtmlDecode(dato)));
			}
		
			if(columns!="") 		
				sect += "<dato>"+columns+"</dato>";
		}
		sect = "<dati>" + sect + "</dati>";
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+sect);
	}		
	void LoadUsers(bool enabled, bool onlinefilter) {
		string tbPrefix = ACM.cmsarea08.DBManager.mainConnection.TablePrefix;
		const string nullo = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<dato></dato>";
		DataSet ds = ACM.cmsarea08.DBManager.mainConnection.Helper_Dataset(" " +
		"SELECT if((DATE_SUB(Now(), interval 31 day)<data_ins),'1','0') as newrec," +
			"lastlogindate,id, enabled, " +
			"username,if(isonline=False,'0','1') as isonline, if(islockedout=False,'0','1') as islockedout " +
			"FROM "+ tbPrefix +"utenti " +
			"where enabled='" + (enabled?"1":"0") + "' " + (onlinefilter?"and isonline='1' ":"") + 
			"order by data_ins desc limit 10");


			if(ds==null) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}
		if(ds.Tables[0].Rows.Count==0) {
			Response.ContentType = "text/xml";		
			Response.Write(nullo);
			return; 
		}		
				
		string sect = "";
		foreach(DataRow dr in ds.Tables[0].Rows) {
			string columns = "";
			for(int i = 0; i<ds.Tables[0].Columns.Count; i++) {
				string dato = "";
				if(dr[i] is byte[]) 
					dato = System.Text.Encoding.UTF8.GetString((byte[])dr[i]);
				else if (dr[i] is DateTime) 
					dato = ((DateTime)dr[i]).ToShortDateString();
				else
					dato = dr[i].ToString();
				columns+=(
					string.Format("<{0}><![CDATA[{1}]]></{0}>", ds.Tables[0].Columns[i].ToString().ToLower(),HttpUtility.HtmlDecode(dato)));
			}
		
			if(columns!="") 		
				sect += "<dato>"+columns+"</dato>";
		}
		sect = "<dati>" + sect + "</dati>";
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+sect);
	}		
	
	void LoadLockCount(string source ) {
		string tbPrefix = ACM.cmsarea08.DBManager.mainConnection.TablePrefix;	
		string query = "select count(*) from " +tbPrefix+ source + " where lockid<>-1 ;";
		object oCheck = ACM.cmsarea08.DBManager.mainConnection.Standard_SC(query);
		string valore = "";
		if(oCheck == null) 
				valore = "<conto>0</conto>";
		else
		 		valore = "<conto>"+oCheck+"</conto>";
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+valore);
	
	}
	
	void CheckPermissionFile (string file ) {
		string reso ="";
		string mioF = ACM.cmsarea08.FileInfo.FilePermissions(file.Trim());	
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		Response.Write("<perm>"+mioF+"</perm>");																	
	}
	void CheckPermissionDir (string dir ) {
		string reso = "";
		string mioF = ACM.cmsarea08.FileInfo.DirectoryPermissions(dir.Trim());	
		Response.ContentType = "text/xml";		
		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		Response.Write("<perm>"+mioF+"</perm>");																	
	}
	
	void getLogList (bool logs ) {
		string reso ="";
		System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(Server.MapPath("/public" + (logs?"/log":"") ) );
		Response.ContentType = "text/xml";		
		if(!dinfo.Exists) {
			Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			Response.Write("<files></files>");																	
		}
		System.IO.FileInfo[] finfo = dinfo.GetFiles( (!logs?"*log*.*":"*.*") );
		if(!logs)
			reso+="<file><fullname>/public/log</fullname><name>log</name><tipo>d</tipo><data>--</data></file>";
		for(int i = 0;i<finfo.Length; i++) {
			reso+="<file><fullname>" + finfo[i].FullName+"</fullname><name>" + 
			finfo[i].Name + "</name><tipo>f</tipo><data>"+finfo[i].LastWriteTime.ToString()+"</data></file>";
		}
		dinfo = null;

		Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		Response.Write("<files>"+reso+"</files>");																	
	}
	
	void readFile(string file) {
		string files = "";
		try {
			System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(file));
			string line;
			while(sr.Peek() != -1)
			{
			   line = sr.ReadLine();
			   files+=HttpUtility.HtmlEncode(line)+"<br/>";
			}
			sr.Close();
			Response.Write(files);		
			
		} catch (Exception ex){
			Response.Write("<h1>there was problems while readind the file</h1>"+ex.ToString());
		}

	}
	
</script>